////////////////////////////////////////////////////////////////////////////////
//                                                                            //
// The MIT License (MIT)                                                      //
//                                                                            //
// Copyright (c) 2013 Charles Teague                                          //
//                                                                            //
// Permission is hereby granted, free of charge, to any person obtaining a    //
// copy of this software and associated documentation files (the "Software"), //
// to deal in the Software without restriction, including without limitation  //
// the rights to use, copy, modify, merge, publish, distribute, sublicense,   //
// and/or sell copies of the Software, and to permit persons to whom the      //
// Software is furnished to do so, subject to the following conditions:       //
//                                                                            //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software.                        //
//                                                                            //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,   //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL    //
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING    //
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER        //
// DEALINGS IN THE SOFTWARE.                                                  //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using RPSDAL;
using RPSDAL.CollectionClasses;
using RPSDAL.EntityClasses;
using RPSDAL.FactoryClasses;
using RPSDAL.DaoClasses;
using RPSDAL.RelationClasses;
using RPSDAL.ValidatorClasses;
using RPSDAL.TypedViewClasses;
using RPSDAL.StoredProcedureCallerClasses;
using RPSDAL.HelperClasses;

using SD.LLBLGen.Pro.ORMSupportClasses;


public partial class ContactGroup : System.Web.UI.Page
{


    protected override void OnInit(System.EventArgs e)
    {
        if (Parameters.LoggedUser != -1) 
        {
            UserEntity eUser = new UserEntity(Parameters.LoggedUser);
            RoleEntity eRole = new RoleEntity(eUser.RoleId);

            if (!eRole.HasEditContactGroup) 
            {
                Parameters.LoggedUser = -1;
                Response.Redirect("Default.aspx");
                return;
            }
        }

        LoadContacts();        
    }

    /// <summary>
    /// load all contacts into the contact list
    /// </summary>
    private void LoadContacts() 
    {
        ContactCollection cContacts = new ContactCollection();
        IPredicateExpression filter = new PredicateExpression();
        filter.Add(ContactFields.Active==true);
        cContacts.GetMulti(filter);

        lstContacts.DataSource = cContacts;
        lstContacts.DataTextField = ContactFields.Name.Name;
        lstContacts.DataValueField = ContactFields.ContactId.Name;
        lstContacts.DataBind();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack) 
        {
            btnMoveToGroup.Attributes.Add("OnClick", "return MoveToGroup()");
            btnRemoveFromGroup.Attributes.Add("OnClick", "return RemoveFromGroup()");
            btnMoveAllToGroup.Attributes.Add("OnClick", "return MoveAllToGroup()");
            btnRemoveAllFromGroup.Attributes.Add("OnClick", "return RemoveAllFromGroup()");


            if (Request.QueryString["id"] != null) 
            {
                if (Request.QueryString["sav"] != null && Request.QueryString["sav"]=="1") 
                {
                    lblContactGroupSaved.Visible = true;
                }

                // load contact group
                try
                {
                    int contactGroupId = Convert.ToInt32(Global.DecryptString(Request.QueryString["id"].ToString()));
                    ContactGroupEntity eContactGroup = new ContactGroupEntity(contactGroupId);

                    txtContactGroupName.Text = eContactGroup.Name;
                    ContactGroupMemberCollection cContactGroupMembers = new ContactGroupMemberCollection();
                    IPredicateExpression filter = new PredicateExpression();
                    filter.Add(ContactGroupMemberFields.ContactGroupId == eContactGroup.ContactGroupId);
                    cContactGroupMembers.GetMulti(filter);

                    string hidden = "";
                    filter = new PredicateExpression();                    
                    for (int i = 0; i < cContactGroupMembers.Count; i++) 
                    {
                        hidden += cContactGroupMembers[i].ContactId.ToString() + ";";
                        ContactEntity eContact = new ContactEntity(cContactGroupMembers[i].ContactId);
                        filter.AddWithAnd(ContactFields.ContactId != eContact.ContactId);

                        if (eContact.Active)
                        {
                            lstGroupContacts.Items.Add(new ListItem(eContact.Name, eContact.ContactId.ToString()));
                        }
                    }
                    filter.AddWithAnd(ContactFields.Active == true);
                    txtGroupContactIds.Value = hidden;

                    ContactCollection cContact = new ContactCollection();
                    cContact.GetMulti(filter);
                    lstContacts.Items.Clear();
                    for (int i = 0; i < cContact.Count; i++) 
                    {
                        lstContacts.Items.Add(new ListItem(cContact[i].Name, cContact[i].ContactId.ToString()));
                    }

                    /*for (int i = 0; i < lstContacts.Items.Count; i++) 
                    {
                        for (int j = 0; j < cContactGroupMembers.Count; j++) 
                        {
                            if (lstContacts.Items[i].Value == cContactGroupMembers[j].ContactId.ToString())
                            {
                                lstContacts.Items[i].Selected = true;
                            }
                        }
                    }*/
                }
                catch { }
            }
        }
    }

    #region user interface

    /// <summary>
    /// insert new contact group or update existing contact group
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Save(object sender, EventArgs e)
    {
        Global.UserLogSave(Parameters.LoggedUser, "Save Contact Group");

        ContactGroupEntity eContactGroup = new ContactGroupEntity();

        if (Page.IsPostBack) 
        {
            try
            {
                int contactGroupId = Convert.ToInt32(Global.DecryptString(Request.QueryString["id"].ToString()));
                eContactGroup = new ContactGroupEntity(contactGroupId);
                ContactGroupMemberCollection cContactGroupMembers = new ContactGroupMemberCollection();
                IPredicateExpression filter = new PredicateExpression();
                filter.Add(ContactGroupMemberFields.ContactGroupId == contactGroupId);
                cContactGroupMembers.DeleteMulti(filter);
            }
            catch { }
        }

        int index = 0;
        if (eContactGroup.IsNew || eContactGroup.Name.ToUpper() != txtContactGroupName.Text.ToUpper())
        {
            ContactGroupCollection cContactGroups = new ContactGroupCollection();

            IPredicateExpression filter2 = new PredicateExpression();
            filter2.Add(ContactGroupFields.Name == txtContactGroupName.Text);
            index = cContactGroups.GetDbCount(filter2);
        }

        eContactGroup.Name = txtContactGroupName.Text;

        


        //cContactGroups.GetMulti(null);
        //int index;
        //bool bExist = false;
        //for (index = 0; index < cContactGroups.Count; index++)
        //{
        //    if (cContactGroups[index].Name == txtContactGroupName.Text)
        //    {
        //        bExist = true;
        //        break;
        //    }
        //}
        if (index == 0)
        {
            lblSteluta.Visible = false;
            lblGroupExist.Visible = false;
        }
        else
        {
            lblSteluta.Visible = true;
            lblGroupExist.Visible = true;
            return;
        }
        eContactGroup.Save();

        string[] contactIds = Request.Form["ctl00$ContentPlaceHolder1$txtGroupContactIds"].Split(';');
        for (int i = 0; i < contactIds.Length - 1; i++)
        {
            try
            {
                ContactGroupMemberEntity eContactGroupMember = new ContactGroupMemberEntity();
                eContactGroupMember.ContactId = Convert.ToInt32(contactIds[i]);
                eContactGroupMember.ContactGroupId = eContactGroup.ContactGroupId;
                eContactGroupMember.Save();
            }
            catch { }
        }

        Response.Redirect("ContactGroup.aspx?id=" + Global.EncryptString(eContactGroup.ContactGroupId.ToString())+"&sav=1");
    }

    /// <summary>
    /// cancel adding a contact group
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Cancel(object sender, EventArgs e)
    {
        Response.Redirect("ContactGroupList.aspx");
    }

    #endregion user interface


}
